package com.xl.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.xl.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是使用dom4j对配置文件解析，封装Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) {
        try {
            Document document = new SAXReader().read(inputStream);
            //根节点 <configuration>
            Element rootElement = document.getRootElement();
            //使用xpath 获取property节点
            List<Element> propertyList = rootElement.selectNodes("//property");
            Properties properties = new Properties();
            for (Element element : propertyList) {
                properties.setProperty(element.attributeValue("name"),element.attributeValue("value"));
            }
            //使用c3p0数据库连接池
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
            comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            comboPooledDataSource.setUser(properties.getProperty("user"));
            comboPooledDataSource.setPassword(properties.getProperty("password"));
            this.configuration.setDataSource(comboPooledDataSource);

            //mapper.xml解析：拿到mapper.xml的全路径--字节输入流--dom4j进行解析
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            for (Element element : mapperList) {
                String mapperPath = element.attributeValue("resource");
                XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(this.configuration);
                xmlMapperBuilder.parse(mapperPath);
            }
        } catch (DocumentException | PropertyVetoException e) {
            e.printStackTrace();
        }
        return configuration;
    }
}
